package cn.mdmm.user.controller;

import java.util.HashMap;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.fastjson.JSON;

import cn.mdmm.user.entity.city.City;
import cn.mdmm.user.entity.system.SysUser;
import cn.mdmm.user.entity.user.request.UserRequest;
import cn.mdmm.user.service.city.CityDubboService;
import cn.mdmm.user.service.user.UserService;
import cn.modoumama.common.exception.ServiceException;

/**
 * Spring Boot HelloWorld 案例
 *
 * Created by bysocket on 16/4/26.
 */
@Controller
public class ApiController {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Reference(version = "1.0")
	CityDubboService cityDubboService;
	@Reference(version = "1.0")
	UserService userService;
	
	@RequestMapping("/")
	@ResponseBody
	public City api() {
		// 从 DB 中获取城市信息
		City city = new City(1L, 2L, "温岭", "是我的故乡");
		cityDubboService.saveCity(city);
		city = cityDubboService.findCityById(city.getId());

		SysUser user = userService.findById(1l);
		logger.info(JSON.toJSONString(user));
		logger.info("CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + city.toString());
		return city;
	}

	@RequestMapping("/user")
	public String user(HashMap<String, Object> map) {
		SysUser user = userService.findById(1l);
		map.put("user", user);
		return "user";
	}
	
	@RequestMapping("/register")
	@ResponseBody
	public String register(HashMap<String, Object> map) {
		UserRequest request = new UserRequest();  
		try {
			request.setPhone("123456");
			userService.register(request);
		} catch (ServiceException e) {
			e.printStackTrace();
		}catch (RpcException e) {
			Throwable e1 = e.getCause();
			if(e1 instanceof ConstraintViolationException){
				ConstraintViolationException constraintException = (ConstraintViolationException) e1;
				Set<ConstraintViolation<?>> Constraints = constraintException.getConstraintViolations();
				for (ConstraintViolation<?> constraintViolation : Constraints) {
					logger.error("{},{}",constraintViolation.getPropertyPath(),constraintViolation.getMessage());
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		return "Validation Save OK";
	}
}
